﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;
using System.Windows;

namespace Unscrambler.Data
{
    public class RandomWordChooser : DependencyObject, IRandomWordChooser
    {
        private List<int> _usedWordsIndices = new List<int>();

        public static readonly DependencyProperty WordsXmlProperty = DependencyProperty.Register("WordsXml",
            typeof(XElement), typeof(RandomWordChooser));
        
        public XElement WordsXml
        {
            get {return (XElement)this.GetValue(WordsXmlProperty);}
            set 
            {
                this.SetValue(WordsXmlProperty, value); 
            }
        }

       
        
        public string GetRandomWord()
        {
            if (WordsXml == null || WordsXml.IsEmpty)
            {
                throw new InvalidOperationException("xml data must be loaded before a random word can be chosen.");
            }

            
            Random rand = new Random();

            int num = int.MinValue;
            while(num == int.MinValue || _usedWordsIndices.Contains(num))
            {
                num = rand.Next(WordsXml.Elements().Count());
                if (AllWordsHaveBeenUsed())
                {
                    _usedWordsIndices.Clear();
                }
            }
            _usedWordsIndices.Add(num);

            string word = WordsXml.Elements().ElementAt(num).Value;
            return word;
        }

        private bool AllWordsHaveBeenUsed()
        {
            return _usedWordsIndices.Count() == WordsXml.Elements().Count();
        }
    }
}
